package com.zhuzi.guicollect.jsl.page;

import com.zhuzi.guicollect.jsl.JslQuestion;
import com.zhuzi.guicollect.utils.DateUtils;
import com.zhuzi.guicollect.utils.HttpUtils;
import io.mikael.urlbuilder.UrlBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: MI
 * @Date: 2021/10/24/21:15
 * @Description:
 */
public class OnlyOnePage extends BasePage {
    @Override
    public void collect(String url, String path, boolean onePage, boolean onlyPublish) {
        UrlBuilder urlBuilder = UrlBuilder.fromString(url);
        if (onlyPublish) {
            urlBuilder = urlBuilder.addParameter("uid", "publisher");
        }
        urlBuilder = urlBuilder.addParameter("sort_key", "add_time").addParameter("sort", "DESC");
        Element bodyFirst = Jsoup.parse(HttpUtils.httpGet(urlBuilder.toString()));
        JslQuestion jslQuestion = JslQuestion.parse(bodyFirst);
        jslQuestion.setUrl(url);
        String name = FilenameUtils.getName(url);
        File filePath = FileUtils.getFile(path,
                name + "-" + StringUtils.replaceEach(jslQuestion.getTitle(), new String[]{"，", "？", "！"}, new String[]{"", "", ""})
                        + "-" + (onlyPublish ? "publisher" : "") + DateUtils.getDateStr() + ".html");
        File picFile = FileUtils.getFile(path, name);

        downPic(picFile, bodyFirst);
        removeOther(bodyFirst);
        Elements replyElesFirst = getReplyEles(picFile, bodyFirst);
        if (jslQuestion.getNumOfReply() == 0) {
            File file = new File(path, name + "-" + jslQuestion.getTitle().trim() + (onlyPublish ? "publisher" : "") + ".html");
            try {
                FileUtils.writeStringToFile(file, bodyFirst.html(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        for (int i = 2; i <= (jslQuestion.getNumOfReply() + 99) / 100; i++) {
            Element body = Jsoup.parse(HttpUtils.httpGet(String.format(questionPage, name, onlyPublish ? "publisher" : "", i)));
            Elements replyEles = getReplyEles(picFile, body);
            replyElesFirst.append(replyEles.toString());
        }
        try {
            FileUtils.writeStringToFile(filePath, bodyFirst.html(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
